package com.thiswhyme.common.utils;

import com.thiswhyme.common.conststant.CommonConstant;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @description: url参数工具
 * @author: thiswhyme
 * @date: 2021/10/12
 */
public class UrlParamUtils {

    /**
     * url query参数转map
     * @param query
     * @return
     */
    public static Map<String, Object> queryToMap(String query) {
        Map<String, Object> map = new HashMap<>(2);
        if (StringUtils.isBlank(query)) {
            return map;
        }
        String[] params = query.split(CommonConstant.AMPERSAND);
        for (String s : params) {
            String[] p = s.split(CommonConstant.EQUAL);
            if (p.length == 2) {
                map.put(p[0], p[1]);
            }
        }
        return map;
    }

    /**
     * map转query
     * @param map
     * @return
     */
    public static String mapToQuery(Map<String, Object> map) {
        if (map == null || map.isEmpty()) {
            return "";
        }

        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            sb.append(entry.getKey())
                    .append(CommonConstant.EQUAL)
                    .append(entry.getValue())
                    .append(CommonConstant.AMPERSAND);
        }

        String result = sb.toString();
        if (result.endsWith(CommonConstant.AMPERSAND)) {
            result = StringUtils.substringBeforeLast(result, CommonConstant.AMPERSAND);
        }
        return result;
    }
}
